<template>
  <div>
    <div class="type-title">
      {{ channelName }}
    </div>
    <Loading v-if="isLoading" />
    <NewsList v-else :news="news" />
    <Pager
      :pageNo="pageNo"
      :pageSize="pageSize"
      :total="total"
      :panelSize="panelSize"
      @pageChange="handleChange"
    />
  </div>
</template>

<script>
import NewsList from '@/components/news/NewsList'
import Pager from '@/components/Pager'
import * as newsServ from '../services/newsService'
import Loading from '../components/Loading'

export default {
  name: 'ChannelNews',
  components: {
    NewsList,
    Pager,
    Loading
  },
  data () {
    return {
      // channelName: '国内焦点',
      pageSize: 15,
      total: 0,
      panelSize: 9,
      news: [],
      isLoading: true
    }
  },
  computed: {
    pageNo () {
      return +this.$route.query.pn || 1
    },
    channelName () {
      var channels = this.$store.state.channels.channels
      if (channels.length > 0) {
        var channel = channels.find(item => item.channelId === this.$route.params.chanId)
        return channel.name
      }
      return ''
    }
  },
  methods: {
    // 设置频道名称
    // async setChannelName () {
    //   var channels = await newsServ.getNewsChannels()
    //   var channel = channels.find(item => item.channelId === this.$route.params.chanId)
    //   this.channelName = channel.name
    // },
    // 设置所有新闻相关数据
    async setNews () {
      this.isLoading = true
      var res = await newsServ.getNews(this.$route.params.chanId, this.pageNo, this.pageSize)
      this.total = res.allNum
      this.news = res.contentlist.slice(0, 10)
      this.isLoading = false
    },
    handleChange (pageNo) {
      // 如何在代码中导航
      // 命令式导航
      // this.$router.push('?pn=' + pageNo)
      this.$router.push({
        // name: 'ChannelNews',
        // params: {
        //   id: this.$route.params.chanId
        // },
        query: {
          pn: pageNo
        }
      })
      this.setNews()
    }
  },
  watch: { // 监控某些数据的变化,当数据变化时要做一些事
    '$route.params.chanId': {
      immediate: true, // 一开始的数据也要当做一种变化
      handler () {
        // this.setChannelName()
        this.setNews()
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.type-title {
  font-size: 2em;
  color: #888;
  border-bottom: 1px solid #ccc;
  padding-bottom: 10px;
}
</style>
